import React, { useState, useEffect } from 'react';
//引入模板添加页面
import AddJuris from "./ui/AddJuris"

import { Button, message, Modal } from 'antd';
//table
import { Table, Input, InputNumber, Popconfirm, Form, Typography } from 'antd';
import { SearchOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { DivStyle } from "./style"
//从model中引入数据请求函数
import { getauthority } from "../../../model/staffModel"
//引入redux
import { useDispatch } from "react-redux"
const Index = () => {
    //设置搜索框信息的state
    const [searchMsg, setSearchMsg] = useState("")
    //搜索框的事件处理函数
    const handleSearch = () => {
        if (searchMsg === "") {
            message.warning("输入为空");
        } else {
            //这里是输出
            console.log(searchMsg)
            setSearchMsg("")
            let searchAfter = data
            searchAfter = searchAfter.filter(item => {
                return item.name === searchMsg
            })
            console.log(searchAfter)
            setData(searchAfter)
        }
    }
    //拟态框的事件处理函数
    const [visible, setVisible] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);


    const showModal = () => {
        setVisible(true);
    };

    const handleOk = (searchMsg) => {
        setConfirmLoading(true);
        setTimeout(() => {
            setData([...data, searchMsg])
            setVisible(false);
            setConfirmLoading(false);
            dispatch({
                type: "addAuthorityList",
                data: searchMsg
            })
        }, 2000);
    };

    const handleCancel = () => {
        console.log('Clicked cancel button');
        setVisible(false);
    };

    //table
    const [data, setData] = useState([]);
    const dispatch = useDispatch()
    async function getTemplateList() {
        let data = await getauthority()
        setData(data)
        dispatch({
            type: "authoritylist",
            data
        })
    }
    useEffect(() => {
        getTemplateList()
    }, []);

    const EditableCell = ({
        editing,
        dataIndex,
        title,
        inputType,
        record,
        index,
        children,
        ...restProps
    }) => {
        const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{
                            margin: 0,
                        }}
                        rules={[
                            {
                                required: true,
                                message: `Please Input ${title}!`,
                            },
                        ]}
                    >
                        {inputNode}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };
    //table
    const [form] = Form.useForm();
    const [editingKey, setEditingKey] = useState('');

    const isEditing = (record) => record.key === editingKey;

    const edit = (record) => {
        form.setFieldsValue({
            name: '',
            number: '',
            level: '',
            authority: '',
            ...record,
        });
        setEditingKey(record.key);
    };

    const cancel = () => {
        setEditingKey('');
    };

    const save = async (key) => {
        try {
            const row = await form.validateFields();
            const newData = [...data];
            const index = newData.findIndex((item) => key === item.key);

            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, { ...item, ...row });
                setData(newData);
                dispatch({
                    type: "updateAuthorityList",
                    data: newData
                })
                setEditingKey('');
            } else {
                newData.push(row);
                setData(newData);
                setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };

    const columns = [
        {
            title: '权限组编号',
            dataIndex: 'number',
            width: '25%',
            editable: true,
        },
        {
            title: '权限组名称',
            dataIndex: 'name',
            width: '15%',
            editable: true,
        },
        {
            title: '权限等级',
            dataIndex: 'level',
            width: '10%',
            editable: true,
        },
        {
            title: '包含权限',
            dataIndex: 'authority',
            width: '40%',
            editable: true,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <Button
                            type="primary"
                            onClick={() => save(record.key)}
                            style={{
                                marginRight: 8,
                            }}
                        >
                            保存
                        </Button>
                        <Popconfirm title="确定取消?" onConfirm={cancel}>
                            <Button>取消</Button>
                        </Popconfirm>
                    </span>
                ) : (
                    <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
                        <Button type="primary">修改</Button>
                    </Typography.Link>
                );
            },
        },
    ];
    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }

        return {
            ...col,
            onCell: (record) => ({
                record,
                inputType: col.dataIndex === 'age' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });
    return (
        <DivStyle>
            <div className="header">
                <span className="part1">
                    <Input placeholder="请输入模板名称" value={searchMsg} onChange={(E) => setSearchMsg(E.target.value)} />
                </span>
                <span className="part2">
                    <Button type="primary" icon={<SearchOutlined />} onClick={() => handleSearch()}>
                        搜索
                    </Button>
                </span>
                <span className="part3">

                    <>
                        <Button type="primary" icon={<PlusCircleOutlined />} onClick={showModal}>
                            添加
                    </Button>
                        <Modal
                            title={"添加模板"}
                            visible={visible}
                            footer={null}
                            onOk={handleOk}
                            confirmLoading={confirmLoading}
                            onCancel={handleCancel}
                        >
                            {<AddJuris ok={handleOk} cancel={handleCancel}></AddJuris>}
                        </Modal>
                    </>
                </span>
            </div>
            <div className="body">
                <Form form={form} component={false}>
                    <Table
                        components={{
                            body: {
                                cell: EditableCell,
                            },
                        }}
                        bordered
                        dataSource={data}
                        columns={mergedColumns}
                        rowClassName="editable-row"
                        pagination={{
                            onChange: cancel,
                        }}
                    />
                </Form>
            </div>
        </DivStyle>
    );
}

export default Index;
